<script lang="tsx">
import { defineComponent, ref } from 'vue';
import { Ban, Pencil, SquarePlay } from '@vben/icons';
import { $t } from '@vben/locales';
import {
  getRolePageApi, updateRoleApi, updateRoleStatusApi,
  getRoleMenuTreeApi, createRoleApi
} from '#/api/system/role';
import BaseDrawer from '#/components/common/base-drawer.vue';
import MenuPermissionTree from '#/components/common/menu-permission-tree.vue';
import StatusComponent from './modules/components/status.vue';
import { usePage } from '#/hooks/page/usePage';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { createMergedObject } from '#/utils/objectMerge';
import { enableDisableOptions, ENABLE_VALUE, DISABLE_VALUE } from "./const"
import { SUPER_ADMIN } from '#/types/const';

export default defineComponent({
  name: 'Role',
  setup() {
    const visible = ref(false);
    const formRef = ref();
    const title = ref('');
    // 菜单权限数据
    const menuList = ref([]);
    const STATUS = 'status';

    const initBaseDrawer = () => ({
      status: ENABLE_VALUE,
      menus: [] as number[],
      description: '',
      name: ''
    })
    // 列配置
    const userColumns = [
      {
        prop: 'name',
        label: $t('system.role.roleName'),
        minWidth: 140,
      },
      {
        prop: 'status',
        label: $t('system.role.status'),
        minWidth: 100,
        formatter: (row: any) => {
          return <StatusComponent status={row.status} enableValue={ENABLE_VALUE} disableValue={DISABLE_VALUE} />;
        }
      },
      {
        prop: 'description',
        label: $t('system.role.description'),
        minWidth: 200,
        showOverflowTooltip: true,
      },
      {
        prop: 'insertUser',
        label: $t('system.role.creator'),
        minWidth: 120,
      },
      {
        prop: 'createTime',
        label: $t('system.role.createTime'),
        minWidth: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
      }
    ];
    // 查询配置
    const queryConfig = [
      {
        prop: 'name',
        label: $t('system.role.roleName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.role.roleName')]),
        // style: {
        //   width: '230px',
        // }
      },
      {
        prop: 'status',
        label: $t('system.role.status'),
        type: 'select',
        placeholder: $t('common.selectPhTxt', [$t('system.role.status')]),
        options: enableDisableOptions,
        // style: {
        //   width: '230px',
        // }
      },
      {
        prop: 'createTime',
        label: $t('system.role.createTime'),
        type: 'daterange',
        'value-format':"YYYY-MM-DD HH:mm:ss",
        placeholder: $t('common.selectPhTxt', [$t('system.role.createTime')]),
        style: {
          width: '350px',
        }
      }
    ];

    const isEnable = (value: string) => value === ENABLE_VALUE;

    // 操作按钮配置
    const operationCommands = [
      {
        key: STATUS,
        icon: Ban,
        render: (row: any, $index: number) => {
          return <el-tooltip effect="dark"
            content={isEnable(row.status) ? $t('common.fiddenTxt') : $t('common.useTxt')} show-after={600}
            placement="top">
            <el-button link icon={isEnable(row.status) ? Ban : SquarePlay}
              onClick={() => tableHandle(STATUS, row, $index)}
              disabled={row.role === SUPER_ADMIN}
            ></el-button>
          </el-tooltip>;
        },
      },
      {
        key: 'edit',
        label: $t('common.editTxt'),
        icon: Pencil,
        render: (row: any, $index: number) => {
          return <el-tooltip effect="dark"
            content={$t('common.editTxt')} show-after={600}
            placement="top">
            <el-button link icon={Pencil} onClick={() => tableHandle('edit', row, $index)}
              disabled={row.role === SUPER_ADMIN}></el-button>
          </el-tooltip>
        },
      },
    ];

    // 自定义操作处理
    const handleCustomCommand = (type: string, data?: any, index?: number) => {
      console.log('Custom operation:', { type, data, index });
      if (type === 'edit' && data.role !== SUPER_ADMIN) {
        visible.value = true;
        title.value = $t('common.editTxt', [$t('system.role.role')]);
        formData.value = createMergedObject(initBaseDrawer(), data);
        formData.value.id = data.id;
        getRoleMenuTree();
      } else if (type === STATUS) {
        updateRoleStatusApi({
          id: data.id,
          status: data.status === ENABLE_VALUE ? DISABLE_VALUE : ENABLE_VALUE
        }).then(() => {
          getTableData()
          if (data.status === ENABLE_VALUE) {
            ElMessage.success($t('system.role.messages.disableSuccess'));
          } else {
            ElMessage.success($t('system.role.messages.enableSuccess'));
          }
        })
      }
    };

    const addRole = () => {
      visible.value = true;
      title.value = $t('common.newTxt', [$t('system.role.role')]);
      formData.value = initBaseDrawer();
      getRoleMenuTree();
    }

    const handleClose = () => {
      visible.value = false;
      title.value = '';
    }

    const handleConfirm = () => {
      if (formRef.value && formRef.value.validate) {
        formRef.value.validate((valid: boolean) => {
          if (valid) {
            let request = formData.value.id ? updateRoleApi : createRoleApi;
            request({ ...formData.value, role: 'Other' }).then(() => {
              getTableData()
              handleClose()
              ElMessage.success($t('common.successTxt'));
            })
          }
        });
      }
    }

    const getRoleMenuTree = async () => {
      const res = await getRoleMenuTreeApi();
      menuList.value = res ?? [];
    }

    const { render, tableHandle, getTableData } = usePage({
      API: {
        get: (data: any) => {
          let params = { ...data };
          if (params.createTime?.length) {
            let [startTime, endTime] = params.createTime;
            params.startTime = startTime
            params.endTime = endTime
            delete params.createTime;
          }
          return getRolePageApi(params)
        }
      },
      columns: userColumns,
      queryColumns: queryConfig,
      commands: operationCommands as any,
      handleCommand: handleCustomCommand,
    });

    const formData = ref(initBaseDrawer() as Record<string, any>);
    // 处理菜单权限选择变化
    const handleMenuChange = (checkedKeys: number[]) => {
      formData.value.menus = checkedKeys;
    };
    // 处理全选事件
    const handleMenuAllCheck = (checkedKeys: number[], isAllChecked: boolean) => {
      console.log('All check changed:', { checkedKeys, isAllChecked });
    };
    // 处理展开收起事件
    const handleMenuExpandCollapse = (isExpanded: boolean) => {
      console.log('Expand/Collapse changed:', isExpanded);
    };
    // 表单数据
    const formColumns = [
      {
        prop: 'name',
        label: $t('system.role.roleName'),
        type: 'input',
        placeholder: $t('common.inputPhTxt', [$t('system.role.roleName')]),
        maxlength: 50,
      },
      {
        prop: 'status',
        label: $t('system.role.status'),
        componentName: 'el-radio-group',
        options: enableDisableOptions,
      },
      {
        prop: 'description',
        label: $t('system.role.roleDescription'),
        type: 'textarea',
        placeholder: $t('common.inputPhTxt', [$t('system.role.roleDescription')]),
        rows: 2,
        maxlength: 100,
        formItemProps: {
          style: {
            width: '100%',
            margin: '0 0 10px 0',
          },
        },
      },
      {
        prop: 'menus',
        label: $t('system.role.menuPermission'),
        formItemProps: {
          labelPosition: 'top',
          style: {
            width: '100%',
            height: 'calc(100% - 140px)',
            display: 'flex',
            flexDirection: 'column',
          },
        },
        render: () => <div class="h-[calc(100vh-320px)] !overflow-y-auto">
          <MenuPermissionTree
            data={menuList.value}
            v-model={formData.value.menus}
            tree-attrs={{
              accordion: false,
              highlightCurrent: true,
              checkStrictly: false,
              autoExpandParent: true,
              emptyText: $t('common.emptyTxt')
            }}
            checkbox-attrs={{
              size: 'default',
              border: false
            }}
            onUpdate:modelValue={handleMenuChange}
            onAllCheck={handleMenuAllCheck}
            onExpandCollapse={handleMenuExpandCollapse}
          />
        </div>
      }
    ];

    const formRules = {
      name: [
        { required: true, message: $t('common.inputPhTxt', [$t('system.role.roleName')]), trigger: 'blur' }
      ],
      isDeleted: [
        { required: true, message: $t('common.inputPhTxt', [$t('system.role.status')]), trigger: 'blur' },
      ],
    };

    const handleFormUpdate = (data: any) => {
      formData.value = data;
    };

    return () =>
      <div>
        {
          render({
            header: <el-button type="primary" onClick={addRole}>{$t('common.newTxt')} </el-button>
          })
        }
        <BaseDrawer
          title={title.value}
          onClose={handleClose}
          onConfirm={handleConfirm}
          modelValue={visible.value}
          showFooter={true}
        >
          <base-form
            ref={formRef}
            columns={formColumns}
            label-position="right"
            inline={true}
            labelWidth="95px"
            modelValue={formData.value}
            class="w-full h-full"
            rules={formRules}
            onUpdate:modelValue={handleFormUpdate}
          />
        </BaseDrawer>
      </div>
  }
});
</script>
